package cn.edu.swufe.surverpark.struts2.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.id.UUIDGenerator;
import org.hibernate.id.UUIDHexGenerator;
import org.springframework.stereotype.Service;

import cn.edu.swufe.surverpark.model.Log;
import cn.edu.swufe.surverpark.struts2.dao.BaseDao;
import cn.edu.swufe.surverpark.struts2.service.LogService;
import cn.edu.swufe.surverpark.util.LogUtil;

/**
 * @author 陈龙 E-mail:529914446@qq.com
 * @version创建时间:2015年5月7日上午3:51:07 类说明
 */
@Service("logService")
public class LogServiceImpl extends BaseServiceImpl<Log> implements LogService {

	@Resource(name = "logDao")
	public void setDao(BaseDao<Log> dao) {
		// TODO Auto-generated method stub
		super.setDao(dao);
	}

	@Override
	public void createLogTable(String tableName) {
		String sql = "create table if not exists " + tableName + " like logs";
		this.executeSQL(sql);
	}

	@Override
	public void saveEntity(Log t) {
		String sql = "insert into "
				+ LogUtil.generateLogTableName(0)
				+ "(ID,OPERPARAMS,OPERRESULT,OPERNAME,OPERATOR,OPERTIME,RESULTMSG)"
				+ " values(?,?,?,?,?,?,?)";
		UUIDHexGenerator uuid = new UUIDHexGenerator();
		String id = (String) uuid.generate(null, null);
		this.executeSQL(sql,id, t.getOperParams(), t.getOperResult(),
				t.getOperName(), t.getOperator(), t.getOperTime(),
				t.getResultMsg());
	}

	@Override
	public List<Log> findNearestLogs(int n) {
		// String sql = "select * from logs_2013_10 union select * from
		// logs_2013_9
		String tableName = LogUtil.generateLogTableName(0);
		String sql = "select table_name from information_schema.tables "
				+ "where table_schema='surveypark' "
				+ "and table_name like 'logs_%' " + "and table_name <='"
				+ tableName + "' " + "order by table_name desc limit 0," + n;
		List list = this.executeSQLQuery(null,sql);

		sql = "";
		for (int i = 0; i < list.size(); i++) {
			if (i == list.size() - 1)
				sql += " select * from " + list.get(i);
			else
				sql += " select * from " + list.get(i) + " union ";

		}
		return this.executeSQLQuery(Log.class,sql);

	}

}
